"""
文件流处理器 - 专门处理大文件上传
"零内存占用的大文件处理"
"""

import os
import uuid
import time
from .core import Request


class StreamFileHandler:
    """流式文件处理器 - 零内存占用的大文件上传"""
    
    def __init__(self, upload_dir="uploads", max_file_size=None):
        self.upload_dir = upload_dir
        self.max_file_size = max_file_size
        
        # 确保上传目录存在
        try:
            os.makedirs(upload_dir, exist_ok=True)
        except OSError as e:
            # 如果目录已存在且不为空，忽略错误
            if e.errno == 39:  # Directory not empty
                pass
            else:
                raise
        
    async def save_stream(self, request: Request, filename=None):
        """保存流式文件"""
        # 生成文件名
        if not filename:
            filename = f"{uuid.uuid4()}_{int(time.time())}.upload"
            
        filepath = os.path.join(self.upload_dir, filename)
        
        # 流式保存
        size = 0
        with open(filepath, "wb") as f:
            async for chunk in request.stream_body():
                f.write(chunk)
                size += len(chunk)
                
                # 检查文件大小限制
                if self.max_file_size and size > self.max_file_size:
                    os.remove(filepath)
                    raise ValueError(f"File too large: {size} > {self.max_file_size}")
                    
        return {
            "filename": filename,
            "filepath": filepath,
            "size": size
        }


# 全局文件处理器实例
file_handler = StreamFileHandler()